﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.Drawing;

using System.Timers;
using System.Windows;



namespace 人脸识别
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Mat matImg;//摄像头图像
        Capture capture;//摄像头对象
        Timer timer;
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                capture = new Capture();
                capture.Start();//摄像头开始工作
                capture.ImageGrabbed += frameProcess;//实时获取图像
            }
            catch (NullReferenceException excpt)
            {
                MessageBox.Show(excpt.Message);
            }


            timer = new Timer(100);
            timer.Elapsed += Timer_Elapsed;
            timer.AutoReset = true;
            this.Closing += MainWindow_Closing;
        
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            capture.Stop();
            capture.Dispose();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {

            Console.WriteLine("执行了");
            DrawFaceRectangle(matImg);
        }

        private void frameProcess(object sender, EventArgs e)
        {

            matImg = new Mat();
            capture.Retrieve(matImg, 0);
           // timer.Start();

            image1.Dispatcher.Invoke(() =>
            {
                DrawFaceRectangle(matImg);
               image1.Source = BitmapSourceConvert.ToBitmapSource(matImg); 
            });
            
        }
        private void DrawFaceRectangle(Mat matImg)
        {

            IImage  image = matImg.ToUMat(Emgu.CV.CvEnum.AccessType.ReadWrite);

            long detectionTime;
            List<Rectangle> faces = new List<Rectangle>();
            List<Rectangle> eyes = new List<Rectangle>();

            DetectFace.Detect(
              image, "haarcascade_frontalface_default.xml", "haarcascade_eye.xml",
              faces, eyes,
              out detectionTime);

            foreach (Rectangle face in faces) { 
                CvInvoke.Rectangle(image, face, new Bgr(Color.Red).MCvScalar, 1);
                Console.WriteLine("检测到人脸，耗时:" + detectionTime);
            }
            foreach (Rectangle eye in eyes) { 
                CvInvoke.Rectangle(image, eye, new Bgr(Color.Blue).MCvScalar, 1);
            }
            if (faces.Count == 1 && eyes.Count == 2) {
           
              
              
            }
        }
    }
}
